package org.redis.cluster.scheduler.second;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.redis.cluster.RedisCluster;
import org.redis.cluster.event.EventPusher;
import org.redis.cluster.plugin.Plugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SecondScheduler implements Plugin,Runnable {
	
	protected final Logger logger=LoggerFactory.getLogger(getClass());
	
	private RedisCluster redisCluster;
	private ScheduledExecutorService scheduleExecutor;

	private final static AtomicInteger second=new AtomicInteger();

	@Override
	public void init(RedisCluster redisCluster) {
		this.redisCluster=redisCluster;
		this.scheduleExecutor=initScheduleExecutor();
	}

	@Override
	public void destroy() {
	}

	protected ScheduledExecutorService initScheduleExecutor() {
		ScheduledExecutorService executor=Executors.newScheduledThreadPool(1);
		executor.scheduleWithFixedDelay(this, 0, 1000*1, TimeUnit.MILLISECONDS);
		return executor;
	}

	@Override
	public void run() {
		EventPusher eventPusher=redisCluster.getEventPusher();
		if(eventPusher==null) {
			return;
		}
		
		SecondScheduleEvent event=new SecondScheduleEvent(second.incrementAndGet());
		eventPusher.push(event);
	}
	
	public static int getSecond() {
		return second.intValue();
	}
}